﻿Imports System.Web.Configuration
Imports System.Collections.Generic

Imports NVelocity
Imports NVelocity.App
Imports NVelocity.Context

Partial Class Public_MasterPage
    Inherits System.Web.UI.MasterPage

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Me.title1.Text += " " + WebConfigurationManager.AppSettings("Version")

        Me.Page.Form.DefaultButton = Me.btnLogin.ID

        If Not IsPostBack Then
            If Request.ServerVariables("HTTP_X_cn") <> "" Then
                Dim userID As String = Request.ServerVariables("HTTP_X_cn")

                If Me.SSOAutoLogin(userID) = True Then
                    Me.PostLoginProcessing(userID)
                    Return
                End If
            End If

            'Me.Master.SiteMapPath.Provider = SiteMap.Providers("PublicSiteMapProvider")
            Me.SiteMapPath.Provider = SiteMap.Providers("PublicSiteMapProvider")

            Me.FixAjaxBug()
            Me.BindMenu()
            Me.BindSystemContactInfo()
            Me.BindBUContactInfo()
            Me.UpdatePublicAuth()

            If Request.QueryString("Login") IsNot Nothing AndAlso Request.QueryString("Login").ToString() = "Y" Then
                Me.divLogin.Visible = True
            Else
                Me.divLogin.Visible = False
                TryCast(Me.FindControl("tdLogin"), HtmlControls.HtmlTableCell).Attributes.Add("background", ResolveUrl("~/images/newImage/login_bg2.gif"))
            End If
        End If

    End Sub

    Protected Sub Menu1_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles Menu1.ItemDataBound
        If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
            Dim dt As Data.DataTable
            Dim dat As New clsData
            Dim sql As New StringBuilder

            sql.AppendFormat("select distinct p.* ")
            sql.AppendFormat("from FD_PublicProgram p ")
            sql.AppendFormat("where p.Parent = '{0}' ", TryCast(e.Item.FindControl("MenuItem"), WebForm_CommonControl_MySlidingMenuGroup).ProgramID)
            sql.AppendFormat("and p.Visible = 'Y' ")
            sql.AppendFormat("order by p.Sequence ")

            dt = dat.GetData(sql.ToString(), Nothing, Data.CommandType.Text, "dt").Tables(0)

            TryCast(e.Item.FindControl("MenuItem"), WebForm_CommonControl_MySlidingMenuGroup).BindGV(dt)
        End If
    End Sub

    Protected Sub btnAdminLogin_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnAdminLogin.Click
        Response.Redirect("~\default.aspx?Login=Y")
    End Sub

    Protected Sub btnMain_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnMain.Click
        Response.Redirect("~\default.aspx")
    End Sub

    Protected Sub btnLogin_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnLogin.Click
        Me.Login()
    End Sub

    Protected Sub btnSSOLogin_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnSSOLogin.Click
        Response.Redirect("~\SSO\default.aspx")
    End Sub

    Protected Sub btnBack_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnBack.Click
        Response.Redirect("~\default.aspx")
    End Sub
End Class

Partial Class Public_MasterPage
    Private Sub BindBUContactInfo()
        Dim dat As New clsData
        Dim sql As New MyStringBuilder
        Dim dt As New Data.DataTable

        sql.Length = 0
        sql.AppendFormat("select ParameterValue as BUContactInfo from FD_SystemParameter ")
        sql.AppendFormat("where ParameterType = 'Home' and ParameterName = 'BUContactInfo' and Active='Y' ")

        Me.fvBUContactInfo.ChangeMode(FormViewMode.ReadOnly)
        Me.fvBUContactInfo.DataSource = dat.GetData(sql)
        Me.fvBUContactInfo.DataBind()

    End Sub

    Private Sub BindSystemContactInfo()
        Dim dat As New clsData
        Dim sql As New MyStringBuilder
        Dim dt As New Data.DataTable

        sql.Length = 0
        sql.AppendFormat("select ParameterValue as SystemContactInfo from FD_SystemParameter ")
        sql.AppendFormat("where ParameterType = 'Home' and ParameterName = 'SystemContactInfo' and Active='Y' ")

        Me.fvSystemContactInfo.ChangeMode(FormViewMode.ReadOnly)
        Me.fvSystemContactInfo.DataSource = dat.GetData(sql)
        Me.fvSystemContactInfo.DataBind()

    End Sub

    Private Sub FixAjaxBug()
        'CalendarExtendar with MultiView + UpdatePanel bug
        'http://dotnetrush.blogspot.com/2008/02/ajax-calendarextender-bug-fixes.html

        Dim url As String = Page.ClientScript.GetWebResourceUrl(GetType(AjaxControlToolkit.ClientCssResourceAttribute), "AjaxControlToolkit.Calendar.Calendar.css")
        Dim myHtmlLink As New HtmlLink()
        myHtmlLink.Href = url
        myHtmlLink.Attributes.Add("rel", "stylesheet")
        myHtmlLink.Attributes.Add("type", "text/css")
        Page.Header.Controls.Add(myHtmlLink)
    End Sub

    Private Sub BindMenu()
        Dim dat As New clsData
        Dim sql As New StringBuilder

        sql.AppendFormat("select distinct p.* ")
        sql.AppendFormat("from FD_PublicProgram p ")
        sql.AppendFormat("where p.Parent = 0 ")
        sql.AppendFormat("order by p.Sequence ")

        Me.Menu1.DataSource = dat.GetData(sql.ToString(), Nothing, Data.CommandType.Text, "dt")
        Me.Menu1.DataBind()

        'Response.Write(clsAuth.GetRoleList)
    End Sub

    Private isVolunteer As Boolean

    Private Function SSOAutoLogin(ByVal userID As String) As Boolean
        Dim dat As New clsData
        Dim sql As New MyStringBuilder

        sql.Length = 0
        sql.AppendFormat("select e.* ")
        sql.AppendFormat("from FD_Employee e ")
        sql.AppendFormat("where e.WindowsID = '{0}' or e.EmployeeID = '{0}' ", userID)

        If dat.GetData(sql).Rows.Count > 0 Then
            Return True
        Else
            MyObj.ShowMessage("公務帳號尚未建檔")
            Return False
        End If
    End Function

    Private Sub Login()
        Dim dat As New clsData
        Dim sql As New MyStringBuilder

        Dim loginResult As Boolean
        Dim requireCheckPassword As Boolean = True
        Dim userID As String = ""

        If WebConfigurationManager.AppSettings("Environment") = "test" Then
            '測試密碼
            If Me.txtPassword.Text = "0000" Then
                requireCheckPassword = False
            End If
        End If

        If Me.txtVerificationCode.Text <> Me.VerificationCode1.VerificationCode Then
            MyObj.ShowMessage(Me.GetLocalResourceObject("SaveData_InvalidVerificationCode"))
            Return
        End If

        Dim dt As Data.DataTable

        sql.Length = 0
        sql.AppendFormat("select e.* ")
        sql.AppendFormat("from FD_Employee e ")
        sql.AppendFormat("where e.WindowsID = '{0}' or e.EmployeeID = '{0}' ", Me.txtUserID.Text)

        dt = dat.GetData(sql)

        '判斷是否為機關人員
        If dt.Rows.Count > 0 Then

            '非公務帳號
            If TypeOf dt.Rows(0)("WindowsID") Is DBNull Or dt.Rows(0)("WindowsID").ToString() = "" Then
                loginResult = True
                userID = dt.Rows(0)("EmployeeID")
                GoTo Login_Success
            ElseIf requireCheckPassword = False Then
                loginResult = True
                userID = dt.Rows(0)("EmployeeID")
                GoTo Login_Success
            Else
                '公務帳號要從 SSO 登入
                Response.Redirect(clsAuth.GetSSOUrl())
                'loginResult = True
                'userID = dt.Rows(0)("EmployeeID")
                'GoTo Login_Success


                'ElseIf requireCheckPassword = False OrElse dat.CheckNTAccount(Me.txtUserID.Text, Me.txtPassword.Text, Me.Domain) = True Then
                '    loginResult = True
                '    userID = dt.Rows(0)("EmployeeID")
                '    GoTo Login_Success
                'Else
                '    MyObj.ShowMessage("密碼輸入錯誤")
                '    Return
            End If
        Else
            MyObj.ShowMessage("您的帳號尚未建檔,請聯絡系統管理人員")
            Return
        End If

Login_Success:
        If loginResult = True Then
            Me.PostLoginProcessing(userID)
        Else
            MyObj.ShowMessage("查無此帳號")
        End If
    End Sub

    ''' <summary>
    ''' 登入成功後之處理
    ''' </summary>
    ''' <param name="userID"></param>
    ''' <remarks></remarks>
    Private Sub PostLoginProcessing(ByVal userID As String)
        Me.BindData(userID)
        'Return
        FormsAuthentication.SetAuthCookie(userID, False)

        '依據此組織資料，判斷表單裡每筆資料之權限
        '登出後清空此資料以節省空間

        '單位權限已停用
        clsAuth.BuildOrganizationAuth(userID)

        '依據此表單權限資料，判斷登入者對表單之權限
        '登出後清空此資料以節省空間
        clsAuth.BuildProgramAuth(userID)

        'MyObj.ShowMessage(clsAuth.GetUser().UserType.Value)
        'MyObj.ShowMessage(clsAuth.GetUser().UserType = My.UserType.Volunteer)
        'Return
        If FormsAuthentication.GetRedirectUrl(userID, False) <> "" Then
            '登入預設首頁,避免ID切換但無原頁面權限
            Response.Redirect(clsAuth.GetDefaultUrl())
            'FormsAuthentication.RedirectFromLoginPage(userID, False)
        Else
            Response.Redirect(clsAuth.GetDefaultUrl())
        End If
    End Sub

    Private ReadOnly Property UserType() As My.UserType
        Get
            Return New My.UserType(Response.Cookies("UserTypeValue").Value)
        End Get
    End Property

    Private Sub BindData(ByVal userID As String)
        Request.Cookies.Clear()
        Response.Cookies.Clear()

        Dim dt As Data.DataTable
        Dim dat As New clsData
        Dim sql As New MyStringBuilder

        '取得個人資訊
        sql.Length = 0
        sql.AppendFormat("select u.* ")
        sql.AppendFormat("from [FD_user] u ")
        sql.AppendFormat("where u.UserID = '{0}' ", userID)

        dt = dat.GetData(sql)

        Response.Cookies("UserName").Value = HttpUtility.UrlEncode(dt.Rows(0)("UserName").ToString())
        Response.Cookies("UserName").Expires = Now.AddMonths(1)

        Response.Cookies("UserTypeValue").Value = dt.Rows(0)("UserType")
        Response.Cookies("UserTypeValue").Expires = Now.AddMonths(1)

        Dim dtInternalUser As Data.DataTable

        '若屬於運用單位人員, 傳回單位資訊
        sql.Length = 0
        sql.AppendFormat("select u.* ")
        sql.AppendFormat("from [FD_InternalUser] u ")
        sql.AppendFormat("where u.UserID = '{0}' ", userID)

        dtInternalUser = dat.GetData(sql)


        Response.Cookies("UOrganizationID").Value = dtInternalUser.Rows(0)("UOrganizationID")
        Response.Cookies("UOrganizationID").Expires = Now.AddMonths(1)

        If Me.UserType = My.UserType.Employee Then
            Response.Cookies("UserType").Value = HttpUtility.UrlEncode("公務帳號")
        ElseIf Me.UserType = My.UserType.Person Then
            Response.Cookies("UserType").Value = HttpUtility.UrlEncode("民間團體")
        End If

        Response.Cookies("VolunteerStatus").Value = dt.Rows(0)("Active")
        Response.Cookies("VolunteerStatus").Expires = Now.AddMonths(1)

        Response.Cookies("RegionID").Value = dt.Rows(0)("RegionID")
        Response.Cookies("RegionID").Expires = Now.AddMonths(1)

        Response.Cookies("RegionType").Value = dt.Rows(0)("RegionType")
        Response.Cookies("RegionType").Expires = Now.AddMonths(1)

        '取得職務列表
        sql.Length = 0
        'sql.AppendFormat("select ru.* ")
        'sql.AppendFormat("from FD_RoleUserMappingView ru ")
        'sql.AppendFormat("where ru.UserID = '{0}' ", userID)
        'sql.AppendFormat("where ru.UserID = '{0}' or ru.UserID='ab5184'", userID)

        sql.AppendFormat("select Value as RoleID ")
        sql.AppendFormat("from fn_GetAllPapasByUserID('{0}') ", userID)

        dt = dat.GetData(sql.ToString(), Nothing, Data.CommandType.Text, "dt").Tables(0)

        Dim roleList As New List(Of String)
        For Each dr As Data.DataRow In dt.Rows
            roleList.Add(dr("RoleID"))
        Next

        'roleList.Add(clsAuth.GetRoleIDByName("Employee"))
        'roleList.Add(clsAuth.GetRoleIDByName("Everyone"))

        Response.Cookies("RoleList").Value = String.Join(",", roleList.ToArray())
        Response.Cookies("RoleList").Expires = Now.AddMonths(1)

        Using scope As New Transactions.TransactionScope
            sql.Length = 0
            sql.AppendFormat("delete FD_UserRoleAuth ")
            sql.AppendFormat("where UserID = '{0}' ", userID)
            dat.AccData(sql)

            For Each roleID As String In roleList
                sql.Length = 0
                sql.AppendFormat("insert FD_UserRoleAuth (UserID, RoleID) ")
                sql.AppendFormat("select '{0}' ", userID)
                sql.AppendFormat(", '{0}' ", roleID)
                sql.AppendFormat("where not exists(select * from FD_UserRoleAuth where UserID='{0}' and RoleID='{1}') ", userID, roleID)

                dat.AccData(sql)
            Next
            scope.Complete()
        End Using

        Response.Cookies("UserType").Expires = Now.AddMonths(1)

    End Sub

    Private Sub UpdatePublicAuth()
        Dim userID As String = ""
        Dim dat As New clsData
        Dim sql As New MyStringBuilder
        Dim roleList As New List(Of String)

        roleList.Add(clsAuth.GetRoleIDByName("Everyone"))

        Using scope As New Transactions.TransactionScope
            sql.Length = 0
            sql.AppendFormat("delete FD_UserRoleAuth ")
            sql.AppendFormat("where UserID = '{0}' ", userID)
            dat.AccData(sql)

            For Each roleID As String In roleList
                sql.Length = 0
                sql.AppendFormat("insert FD_UserRoleAuth (UserID, RoleID) ")
                sql.AppendFormat("select '{0}' ", userID)
                sql.AppendFormat(", '{0}' ", roleID)

                dat.AccData(sql)
            Next
            scope.Complete()
        End Using
    End Sub

    Private ReadOnly Property Domain()
        Get
            Return WebConfigurationManager.AppSettings("NTDomain")
        End Get
    End Property

    Public ReadOnly Property SiteMapPath() As SiteMapPath
        Get
            Return Me.SiteMapPath1
        End Get
    End Property

End Class